#include <iostream>

using namespace std;

struct ListNode {
    int val;
    ListNode* next;
    ListNode() : val(0), next(nullptr) {}
    ListNode(int val) : val(val), next(nullptr) {}
    ListNode(int val, ListNode* next) : val(val), next(next) {}
};

ListNode* rotateRight(ListNode* head, int k) {
    if (k == 0 || head == nullptr || head->next == nullptr) {
        return head;
    }

    int total = 1;
    ListNode* cur = head;
    while (cur->next != nullptr) {
        total++;
        cur = cur->next;
    }

    int num = total - k % total;
    if (num == total) {
        return head;
    }

    // 首尾相接
    cur->next = head;

    // 找到新头节点前一个节点断开
    for (int n = 1; n < total - num; n++) {
        head = head->next;
    }

    ListNode* newhead = head->next;
    head->next = nullptr;

    return newhead;
}

void printList(ListNode* head) {
    cout << "[";
    while (head != nullptr) {
        cout << head->val << ",";
        head = head->next;
    }
    cout << "]" << endl;
}

int main() {
    ListNode* l = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4, new ListNode(5)))));
    printList(l);
    printList(rotateRight(l, 2));

    return 0;
}